#!/bin/bash

echo "=== Nginx 测试开始 ==="

# 启动 Nginx 服务
echo "启动 Nginx 服务..."
docker-compose -f nginx-compose.yml up -d

# 等待 Nginx 启动
echo "等待 Nginx 启动..."
sleep 5

# 检查容器状态
if ! docker ps | grep -q "test-nginx"; then
    echo "❌ Nginx 容器启动失败"
    exit 1
fi

echo "✅ Nginx 容器启动成功"

# 测试健康检查
echo "测试健康检查..."
if curl -s http://localhost:8080/health | grep -q "healthy"; then
    echo "✅ 健康检查通过"
else
    echo "❌ 健康检查失败"
    exit 1
fi

# 测试静态文件服务
echo "测试静态文件服务..."
if curl -s http://localhost:8080/ | grep -q "Nginx 测试成功"; then
    echo "✅ 静态文件服务正常"
else
    echo "❌ 静态文件服务失败"
    exit 1
fi

# 测试 API 代理
echo "测试 API 代理..."
API_RESPONSE=$(curl -s http://localhost:8080/api/test)
if echo "$API_RESPONSE" | grep -q "API proxy test"; then
    echo "✅ API 代理测试通过"
else
    echo "❌ API 代理测试失败"
    exit 1
fi

# 测试状态页面
echo "测试状态页面..."
if curl -s http://localhost:8080/status | grep -q "Active connections"; then
    echo "✅ 状态页面正常"
else
    echo "❌ 状态页面失败"
    exit 1
fi

# 测试 404 错误处理
echo "测试 404 错误处理..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/nonexistent)
if [ "$HTTP_CODE" = "404" ]; then
    echo "✅ 404 错误处理正常"
else
    echo "❌ 404 错误处理失败，返回码: $HTTP_CODE"
fi

# 性能测试 - 并发请求
echo "执行并发性能测试..."
for i in {1..10}; do
    curl -s http://localhost:8080/health > /dev/null &
done
wait
echo "✅ 并发测试完成"

# 检查访问日志
echo "检查访问日志..."
LOG_COUNT=$(docker exec test-nginx wc -l /var/log/nginx/access.log | cut -d' ' -f1)
if [ "$LOG_COUNT" -gt 0 ]; then
    echo "✅ 访问日志正常，共 $LOG_COUNT 条记录"
else
    echo "⚠️  访问日志为空"
fi

# 检查错误日志
echo "检查错误日志..."
ERROR_COUNT=$(docker exec test-nginx wc -l /var/log/nginx/error.log | cut -d' ' -f1 2>/dev/null || echo "0")
echo "错误日志条数: $ERROR_COUNT"

echo "=== Nginx 测试完成 ==="

# 选择是否停止服务
read -p "是否停止 Nginx 服务? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    docker-compose -f nginx-compose.yml down
    echo "Nginx 服务已停止"
fi